package com.foxcai.novel.action;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Calendar;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import com.foxcai.novel.base.ConfConstants;

/**
 * @file_name 文件名及文件之后的参数.最好为a.jsf?fileId=aaaa
 * @path 文件所在的路径.相对于根目录而言的.
 * @realName 文件要保存的名字
 * @realPath 文件要保存的真实路径。默认与文件所在的目录相同。
 */
public class ToHtmlForTemplate extends HttpServlet {

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		PrintWriter out = response.getWriter();

		String tempPath = "";
		String outPath = "";

		String realName = request.getParameter("realName");
		String realPath = request.getParameter("realPath");

		if (realName == null || realName.equals("")) {
			Calendar calendar = Calendar.getInstance();
			realName = String.valueOf(calendar.getTimeInMillis());
		}

		if (realPath == null || realPath.equals("")) {
			outPath = ConfConstants.CONTEXT_PATH + "\\" + realName + ".html";
		} else {
			outPath = ConfConstants.CONTEXT_PATH + "\\" + realPath + "\\"
					+ realName + ".html";
		}

		tempPath = ConfConstants.CONTEXT_PATH + "\\template\\view.htm";
		out.print(tempPath);

		String title = "";
		String content = "";
		String templateContent = "";
		FileInputStream fileinputstream = new FileInputStream(tempPath);// 读取模块文件
		int lenght = fileinputstream.available();
		byte bytes[] = new byte[lenght];
		fileinputstream.read(bytes);
		fileinputstream.close();
		templateContent = new String(bytes);
		out.print(templateContent);
		templateContent = templateContent.replaceAll("##KeyWords##", title);
		templateContent = templateContent
				.replaceAll("##ContentBody##", content);
		out.print(templateContent);

		FileOutputStream fileoutputstream = new FileOutputStream(outPath);// 建立文件输出流
		out.print("文件输出路径:<br>");
		out.print(outPath);
		byte tag_bytes[] = templateContent.getBytes();
		fileoutputstream.write(tag_bytes);
		fileoutputstream.close();

		out.print("<p align=center><font size=3 color=red>success.</font></p>");
	}
}